# -*- coding: utf-8 -*-

import os


import resource_type
import pystore.core.framework.file_system as file_system
import pystore.core.framework.os2 as os2
import pystore.core.framework.path as path
from   pystore.core.framework.path import Path2
from   pystore.core.resource import Project,IStoreManager,_ResourceInfo
import pystore.core.config as config


'''
Project 在初始化_ResourceInfo时加入了localProjectPath:Path2属性供本模块自己使用
'''  

class LocalStoreManager(IStoreManager):
    
    def __init__(self):
        self.fileSystem = file_system.getFileSystem('file')

    def createProject(self,project,resourceAttributes):
        '''
        args:
          resourceAttributes: 其中必须包含键值:Path projectPath
        '''
        projectLocalPath = resourceAttributes['projectPath']
        fileStore = self.fileSystem.getFileStore(projectLocalPath)
        fileStore.makedir()
        
        db = config.openProjectsDb()
        db[project.getName()] = str(projectLocalPath)
        db.close()
        
        result = _ResourceInfo.create(resource_type.PROJECT,fileStore.fetchInfo())
        result.projectLocalPath= projectLocalPath
        return result
    
    def getFileStore(self,resource):
        assert resource.getType() != resource_type.ROOT
        
        db = config.openProjectsDb()
        result = None
        projectName = resource.getProject().getName()
        if db.has_key(projectName):
            localPath = Path2.parse(db[projectName]).append(resource.getPath().removeFirstSegments(1))
            result = self.fileSystem.getFileStore(localPath)
        db.close()
        return result
    
    def getProjectStores(self):
        '''
        getProjectStores() -> dict
        
        return :
           {basestring projectName:FileStore projectStore...}
        '''
        db = config.openProjectsDb()
        result = {}
        for name,localPath in db.items():
            result[name]=self.fileSystem.getFileStore(Path2.parse(localPath))
        db.close() 
        return result